// 文章页面
<template>
  <div class="articles-container">
    <!-- 数据可视化图表 -->
    <div class="chart-container">
      <div id="articleChart" style="width: 100%; height: 400px"></div>
    </div>

    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="搜索文章标题"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate">
        新增文章
      </el-button>
    </div>

    <el-table
      ref="articlesTable"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      v-loading="loading"
      element-loading-text="数据加载中..."
      element-loading-spinner="el-icon-loading"
      key="articlesTable"
    >
      <el-table-column prop="_id" label="ID" width="80" align="center" />
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="name" label="作者" width="120" align="center" />
      <el-table-column prop="type" label="分类" width="120" align="center" />
      <el-table-column
        prop="time"
        label="发布时间"
        width="160"
        align="center"
      />
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import axios from "axios";
import * as echarts from "echarts";

export default {
  name: "ArticlesManagement",
  components: { Pagination },
  data() {
    return {
      chart: null,
      list: [], //文章列表数组
      SearchForPreviousArticles: [], //搜索前的数组
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        title: "", //搜索的值
      },
      // 页数，每一页展示的文章数量
    };
  },
  mounted() {
    // 初始化图形化数据统计
    this.initChart();
    // 挂载完成时调用API
    this.sqContent();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 初始化图形化数据统计函数
    initChart() {
      this.chart = echarts.init(document.getElementById("articleChart"));
      this.updateChart();
    },
    // 更新图形化数据统计函数
    updateChart() {
      const categoryCount = this.list.reduce((acc, item) => {
        acc[item.type] = (acc[item.type] || 0) + 1;
        return acc;
      }, {});

      const option = {
        title: { text: "文章数据统计", left: "center" },
        tooltip: { trigger: "item" },
        grid: { top: "20%", containLabel: true },
        xAxis: { type: "category", data: Object.keys(categoryCount) },
        yAxis: { type: "value" },
        series: [
          {
            name: "文章数量",
            type: "bar",
            data: Object.values(categoryCount),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#83bff6" },
                { offset: 0.5, color: "#188df0" },
                { offset: 1, color: "#188df0" },
              ]),
            },
          },
        ],
      };
      this.chart.setOption(option);
    },
    async getList() {
      this.loading = true;
      try {
        // 模拟数据获取
        this.list = [];

        this.total = 1;
        this.updateChart();
      } catch (error) {
        console.log("获取模拟数据:", error);
        this.$message.warning("正在使用模拟数据");
      } finally {
        this.loading = false;
      }
    },
    // 搜索处理
    handleFilter() {
      this.listQuery.page = 1;
      // this.getList();
      this.list = this.SearchForPreviousArticles.filter((item) =>
        item.title.includes(this.listQuery.title)
      );
    },
    // 跳转文章编辑页面函数
    handleCreate() {
      this.$router.push({
        name: "ArticleEdit",
      });
    },
    // 传入数据到编辑页面
    handleEdit(article) {
      // article是该文章的所有数据
      this.$router.push({
        name: "ArticleEdit",
        params: {
          id: article._id,
          Context: article.Context,
          title: article.title,
          name: article.name,
          type: article.type,
        },
        query: {
          Context: article.Context,
          title: article.title,
          name: article.name,
          type: article.type,
        },
      });
    },
    // 删除单条数据
    handleDelete(article) {
      this.$confirm("确认删除该文章吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios.delete(`http://127.0.0.1:3000/api/${article._id}`).then(() => {
            this.$message.success("删除成功");
            this.sqContent();
          });
        })
        .catch(() => {
          this.$message.error("删除失败：");
        });
    },
    // 搜索全部的文章数据
    sqContent() {
      axios.get("http://127.0.0.1:3000/api").then(
        (response) => {
          // 将api数据赋值给data
          console.log(response.data.data);
          const data = response.data.data;
          // 遍历data里面的time替换正则
          data.forEach((item) => {
            const str = item.time;
            const match = str.match(/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/);
            if (match) {
              const result = `${match[1]} ${match[2]}`;
              item.time = result;
            }
          });
          // 最终将data数据赋值给list
          this.list = data;
          this.total = data.length;
          this.SearchForPreviousArticles = data;
          // 更新文章数据统计图形化界面
          this.updateChart();
        },
        (error) => {
          console.log(error);
        }
      );
    },
  },
};
</script>

<style scoped>
.articles-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-item {
  transition: all 0.3s;
}

.filter-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-table {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.el-button--primary {
  background: linear-gradient(to right, #409eff, #64b5f6);
  border: none;
  transition: all 0.3s;
}

.el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
